<template>
  <div class="content">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: 'warehouseStock' }"
        >仓库库存</el-breadcrumb-item
      >
      <el-breadcrumb-item>库存调整列表</el-breadcrumb-item>
      <el-breadcrumb-item v-if="!obj.isNewO">填写库存调拨</el-breadcrumb-item>
      <el-breadcrumb-item v-else>重开库存调拨</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="context">
      <div class="left">
        <div class="top">库存调拨</div>
        <div class="tableBorder">
          <div class="title">
            <span>调拨编号：{{ table.oddNumber }}</span>
            <span>
              <span style="margin-right: 20px"
                >申请人：{{ table.createdByName }}
              </span>
              <span> 创建时间：{{ $moment(table.createdTime) }}</span>
            </span>
          </div>
          <el-table
            ref="moviesTable"
            @row-click="openDetails"
            @selection-change="selectChange"
            :data="table.goodsList"
          >
            <el-table-column type="selection" width="50"> </el-table-column>
            <el-table-column
              label="序号"
              type="index"
              width="50"
            ></el-table-column>
            <el-table-column label="商品信息" prop="title"></el-table-column>
            <el-table-column
              v-for="(item, index) in wareList.list"
              :key="index"
              :label="item.name"
            >
              <template slot-scope="scope">
                <div
                  v-if="
                    scope.row.warehouses &&
                      scope.row.warehouses.find((res) => res.warId == item.id)
                  "
                >
                  <!-- <el-tooltip
                    class="item"
                    effect="dark"
                    content="实时库存"
                    :open-delay="300"
                    placement="right-start"
                    v-if="type == 1"
                  >
                    <div>
                      {{
                        scope.row.warehouses.find((res) => res.warId == item.id)
                          .laterQuantity
                          ? scope.row.warehouses.find(
                              (res) => res.warId == item.id
                            ).laterQuantity
                          : 0
                      }}
                    </div>
                  </el-tooltip> -->
                  <el-tooltip
                    :open-delay="300"
                    class="item"
                    effect="dark"
                    content="提交时库存"
                    placement="right-start"
                    ><div>
                      {{
                        type == 1
                          ? scope.row.warehouses.find(
                              (res) => res.warId == item.id
                            ).laterQuantity
                          : scope.row.warehouses.find(
                              (res) => res.warId == item.id
                            ).laterQuantity
                      }}
                    </div></el-tooltip
                  >
                  <el-tooltip
                    :open-delay="300"
                    class="item"
                    effect="dark"
                    content="修改库存"
                    placement="right-start"
                  >
                    <div>
                      {{
                        scope.row.warehouses.find((res) => res.warId == item.id)
                          .difference >= 0
                          ? "+" +
                            scope.row.warehouses.find(
                              (res) => res.warId == item.id
                            ).difference
                          : scope.row.warehouses.find(
                              (res) => res.warId == item.id
                            ).difference
                      }}
                    </div></el-tooltip
                  >
                </div>
                <div v-else>
                  <!-- <el-tooltip
                    :open-delay="300"
                    class="item"
                    effect="dark"
                    content="实时库存"
                    placement="right-start"
                    v-if="type == 1"
                  >
                    <div>
                      {{ 0 }}
                    </div>
                  </el-tooltip> -->
                  <el-tooltip
                    :open-delay="300"
                    class="item"
                    effect="dark"
                    content="实际库存"
                    placement="right-start"
                    ><div>
                      {{ 0 }}
                    </div></el-tooltip
                  >
                  <el-tooltip
                    :open-delay="300"
                    class="item"
                    effect="dark"
                    content="修改库存"
                    placement="right-start"
                  >
                    <div>+0</div></el-tooltip
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="right">
        <div class="title">
          <span>操作</span>
        </div>
        <el-form
          v-if="selectObj.brandId != undefined || selectArray.length > 1"
          ref="form"
          :model="form"
          label-width="80px"
        >
          <el-form-item v-if="isHideForm" label="商品名称">
            <el-input size="small" disabled :value="selectObj.title"></el-input>
          </el-form-item>
          <el-form-item v-if="isHideForm" label="库存总数">
            <el-input size="small" disabled :value="selectObj.count"></el-input>
          </el-form-item>
          <el-form-item
            label="仓库数量"
            v-if="selectObj.warehouses && isHideForm"
          >
            <el-input
              disabled
              size="small"
              :value="selectObj.history"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="isHideForm" label="调拨仓库">
            <div
              v-for="(ite, index) in selectObj.warehouses"
              :key="index"
              v-if="ite.type == 0 || ite.type == undefined"
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <el-select
                :value="ite.warName"
                size="mini"
                value-key="id"
                placeholder="请选择"
                :disabled="ite.type == 0"
                @change="myWareListChange($event, ite)"
              >
                <el-option
                  v-for="item in wareList.list"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
              <div style="display: flex; align-items: center">
                <el-input-number
                  size="mini"
                  :min="0"
                  style="margin-right: 10px"
                  placeholder="请输入库存数量"
                  v-model="ite.laterQuantity"
                  @change="inputChange(ite)"
                ></el-input-number>

                <i
                  class="el-icon-remove-outline"
                  style="cursor: pointer"
                  @click="deleteMyWare(ite, ite.type != undefined ? 1 : 0)"
                ></i>
              </div>
            </div>
            <i
              v-if="
                selectObj.warehouses &&
                  selectObj.warehouses.length < wareList.list.length
              "
              class="el-icon-circle-plus-outline"
              style="cursor: pointer"
              @click="addMyWareList"
            ></i>
          </el-form-item>
          <el-form-item label="调拨原因">
            <el-select
              style="width: 100%"
              v-model="selectObj.tempSelect"
              ref="select"
              placeholder="请选择"
              size="mini"
              clearable
              value-key="id"
              @change="whySelect"
              @visible-change="(v) => visibleChange(v, 'select', selectClick)"
            >
              <el-option
                v-for="item in whyList.list"
                :key="item.id"
                :label="item.deliveryName"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 空数据 -->
        <div class="nodate" v-else>
          <img src="../../../../assets/kong.png" alt="" />
          <span>请选择左侧信息</span>
        </div>
      </div>
      <el-dialog
        title="管理调拨原因"
        append-to-body
        width="30%"
        :visible.sync="dialogFormVisible"
      >
        <div class="dialogContent">
          <el-form label-width="80px">
            <el-form-item label="添加原因">
              <div class="add">
                <el-input v-model="whyValue" size="mini"></el-input
                ><i
                  style="margin-left: 20px; cursor: pointer"
                  class="el-icon-circle-plus-outline"
                  @click="addWhy"
                ></i>
              </div>
            </el-form-item>
          </el-form>
          <div
            class="whyList"
            style="pading: 2px 0px; height: 405px; overflow: auto"
          >
            <div
              v-for="(item, index) in whyList.list"
              :key="index"
              @dblclick="updateItem($event, item)"
              style="
                margin-bottom: 5px;
                display: flex;
                align-items: center;
                height: 40px;
                padding-left: 10px;
              "
            >
              <i
                v-if="id != item.id"
                class="el-icon-remove-outline"
                @click="deleteWhy(item.id)"
              ></i>
              <span v-if="id != item.id" style="margin-left: 10px">{{
                item.deliveryName
              }}</span>
              <input
                v-focus
                @blur="updateBlur($event.target.value, item)"
                v-if="id == item.id"
                type="text"
                style="height: 40px"
              />
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
    <div style="height:40px;"></div>
    <div class="submit">
      <el-button size="mini" @click="$router.go(-1)">取消</el-button>
      <el-button size="mini" type="primary" @click="addAllot">提交</el-button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      type: this.$route.query ? this.$route.query.type : 0,
      deliveryName: "",
      selectArray: [],
      isHideForm: true,
      id: "",
      whyValue: "",
      dialogFormVisible: false, //管理调拨原因的对话框
      table: {
        list: [],
      }, //列表数据
      form: {}, //表单数据
      wareList: {
        list: [],
      }, //仓库列表
      whyList: {
        list: [],
      }, //调拨原因
      selectObj: {
        warehouses: [],
        title: "",
      },
      obj: '',
      cart: '',
    };
  },
  activated() {
    this.axios.post("order/comm/commWarehouse/list",{
        pageSize:999,
        pageNo:1
      }).then((res) => {
      //仓库数据接口
      this.wareList = res.data;
      this.wareList.list = this.wareList.list.reverse();
    });
    this.getWhyList();
    if (this.$route.query.obj) {
      this.reset();
      this.getList();
      this.obj = JSON.parse(this.$route.query.obj);
    }
    this.cart= JSON.parse(localStorage.getItem("cart"));
    // if (this.$route.query.type == 1) {
    //   this.reset();
    //   this.axios
    //     .get(
    //       "/order/stockControl/allotDetails?oddNumber=" +
    //         this.$route.query.oddNumber
    //     )
    //     .then((res) => {
    //       if (res.code == 0) {
    //         for (let item of res.data.goods) {
    //           item.history = "";
    //           item.warehouses = item.wars;
    //           item.title = item.goodsName;
    //           item.goodsType = item.gtype;
    //           for (let ite of item.warehouses) {
    //             item.history += ite.warName + ite.realTimeQuantity + "  ";
    //             ite.type = 0;
    //             ite.tempQuantity = ite.frontQuantity;
    //             ite.laterQuantity = ite.realTimeQuantity;
    //             ite.frontQuantity = ite.realTimeQuantity;
    //             ite.difference = 0;
    //           }
    //         }
    //         res.data.goodsList = res.data.goods;
    //         this.table = res.data;
    //       } else {
    //         this.$message.error(res.message);
    //         this.$router.go(-1);
    //       }
    //     });
    // }
  },
  methods: {
    whySelect(e) {
      if (this.selectArray.length > 1) {
        this.selectArray.forEach((res) => {
          this.$set(res, "warAdId", e.id);
          this.$set(res, "warAdName", e.deliveryName);
        });
      } else {
        this.$set(this.selectObj, "warAdId", e.id);
        this.$set(this.selectObj, "warAdName", e.deliveryName);
      }

      this.$forceUpdate();
    },
    inputChange(e) {
      if (!e.laterQuantity) {
        e.laterQuantity = 0;
      }
      this.$set(e, "difference", e.laterQuantity - e.frontQuantity);
    },
    selectChange(e) {
      if (e.length < 2) {
        this.isHideForm = true;
      } else {
        this.isHideForm = false;
      }
      // if (e.length) {
      //   this.selectObj = e[0];
      // }
      this.selectArray = e;
    },
    openDetails(row) {
      this.$set(this, "selectObj", row);
      if (row.warAdId) {
        this.$set(
          this.selectObj,
          "tempSelect",
          this.whyList.list.find((res) => res.id == row.warAdId)
        );
      }
    },

    // 删除调整过的商品缓存//
    moreDelect() {
      let gids = JSON.parse(this.$route.query.obj).gids;

      for (let i = 0; i < gids.length; i++) {
        if (JSON.parse(this.$route.query.obj).gType == "1") {
          if (
            this.cart.goodList.find(
              (res) => res.id == JSON.parse(this.$route.query.obj).gids[i]
            )
          ) {
            this.cart.goodList = this.cart.goodList.filter(
              (res) => res.id != JSON.parse(this.$route.query.obj).gids[i]
            );
          }
        } else {
          this.cart.giftList = this.cart.giftList.filter(
            (res) => res.id != JSON.parse(this.$route.query.obj).gids[i]
          );
        }
      }

      localStorage.setItem(
        "cart",
        JSON.stringify({
          goodList: this.cart.goodList,
          giftList: this.cart.giftList,
        })
      );
    },

    addAllot() {
      let obj = undefined;
      if (this.$route.query.obj) {
        let obj = JSON.parse(this.$route.query.obj);
      }
      let temp = false;
      this.table.goodsList.forEach((res) => {
        if (res.warehouses) {
          if (res.oldWars > res.warehouses.length) {
            this.$message.warning("仓库数量不一致");
            temp = true;
          }
          res.warehouses.forEach((t) => {
            if (!t.warId) {
              this.$message.warning("有仓库没选择请检查一下");
              temp = true;
            }
          });
        }
      });
      if (!temp) {
        if (!this.$route.query.type) {
          this.table.goodsList.forEach((res) => {
            let lTemp = 0;
            let fTemp = 0;
            if (res.warehouses) {
              res.warehouses.forEach((e) => (lTemp += e.laterQuantity));
              res.warehouses.forEach((e) => (fTemp += e.frontQuantity));
            }
            res.warRequestList = res.warehouses ? res.warehouses : [];
            res.goodsType = obj ? obj.gType : this.obj.gType;
            res.goodsName = res.title;
            res.goodsId = res.id;
            res.laterQuantity = lTemp;
            res.frontQuantity = fTemp;
          });
          this.axios
            .post("/order/stockControl/addAllot", {
              goodsList: this.table.goodsList,
              type: 1,
              createdById: sessionStorage.getItem("user_id"),
              oddNumber: this.table.oddNumber,
              createdByName: this.table.createdByName,
            })
            .then((res) => {
              let obj = JSON.parse(this.$route.query.obj);
              if (res.code == 0) {
                this.$message.success("提交成功");
                if (obj.isNewO) {
                  this.axios.get(
                    "/order/stockControl/close?oddNumber=" +
                      obj.isNewO +
                      "&type=1",
                    {
                      isLoading: false,
                    }
                  );
                }
                if (!this.obj.isNewO) {
                  this.moreDelect();
                }
                this.reset();
                this.$store.commit("clearToolItem", "/wareUpdate");
                this.$router.go(-1);
              } else {
                this.$message.error(res.message);
              }
            });
        } else {
          this.table.goods.forEach((res) => {
            let lTemp = 0;
            res.warehouses.forEach((e) => (lTemp += e.realTimeQuantity));
            let fTemp = 0;
            res.warehouses.forEach((e) => (fTemp += e.frontQuantity));
            res.laterQuantity = lTemp;
            res.frontQuantity = fTemp;
            res.warRequestList = res.warehouses;
          });
          this.axios
            .post("/order/stockControl/updateAllot", {
              createdById: this.table.proposer,
              createdByName: this.table.proposerName,
              createdTimeL: this.$moment(this.table.createdTime),
              goodsList: this.table.goods,
              oddNumber: this.table.oddNumbers,
              type: 1,
            })
            .then((res) => {
              if (res.code == 0) {
                this.$message.success("修改成功");
                this.reset();
                this.$store.commit("clearToolItem", "/wareUpdate");
                this.$router.go(-1);
              } else {
                this.$message.error(res.message);
              }
            });
        }
      }
    },
    reset() {
      this.table = {
        list: [],
        pageNo: 1,
        pageSize: 10,
      };
      this.selectArray = [];
      this.form = {};
      this.selectObj = {};
      this.deliveryName = "";
    },
    getList() {
      let obj = JSON.parse(this.$route.query.obj);
      this.axios
        .post("/order/stockControl/fillInAllotNumber", {
          gids: obj.gids,
          gtype: obj.gType,
          type: "TB",
        })
        .then((res) => {
          if (res.code == 0) {
            this.table = res.data;
            this.table.list = this.table.goodsList;
            console.log(res.data.goodsList);
            for (let item of res.data.goodsList) {
              item.oldWars = item.warehouses ? item.warehouses.length : 0;
              item.history = "";
              item.count = 0;
              if (item.warehouses) {
                for (let temp of item.warehouses) {
                  item.count += temp.number;
                  item.history += temp.warName + "" + temp.number + "  ";
                  this.$set(temp, "type", 0);
                  this.$set(temp, "difference", 0);
                  this.$set(temp, "frontQuantity", temp.number);
                  this.$set(temp, "laterQuantity", temp.number);
                }
              }
            }
          } else {
            this.$message.error(res.message);
            // this.$router.go(-1);
          }
        });
    },
    updateBlur(e1, e2) {
      this.id = "";
      if (e1 == e2.deliveryName || !e1.replaceAll(" ", "").length) {
        this.$message.warning("名字没有任何改变");
        return;
      }
      this.axios
        .post("/order/warAdjustmentConfig/update", {
          request: {
            id: e2.id,
            deliveryName: e1,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.getWhyList();
            this.$message.success("修改成功");
          } else {
            this.$message.error(res.message);
          }
        });
    },
    updateItem(e1, e2) {
      this.id = e2.id;
    },
    draggableInput(e) {
      this.$set(this.whyList, "list", e);
    },
    //添加管理调拨原因
    addWhy: _.debounce(function() {
      if (this.whyValue.replaceAll(" ", "").length) {
        this.axios
          .post("/order/warAdjustmentConfig/add", {
            request: {
              deliveryName: this.whyValue,
            },
          })
          .then((res) => {
            if (res.code === 0) {
              this.$message.success("添加成功");
              this.whyValue = "";
              this.getWhyList();
            } else {
              this.$message.warning(res.message);
            }
          });
      } else {
        this.$message.warning("请输入调拨原因");
      }
    }, 500),
    deleteWhy(e) {
      this.axios
        .get("/order/warAdjustmentConfig/delete?id=" + e)
        .then((res) => {
          if (res.code === 0) {
            this.$message.success("删除成功");
            this.getWhyList();
          } else {
            this.$message.warning(res.message);
          }
        });
    },
    getWhyList() {
      this.axios
        .post("/order/warAdjustmentConfig/list", { request: {} })
        .then((res) => {
          this.$set(this, "whyList", res.data);
        });
    },
    //删除现在的仓库
    deleteMyWare(e, t) {
      if (t) {
        let temp = this.selectObj.warehouses.find(
          (res) => res.warId === e.warId
        );
        temp.type = 1;
        temp.difference = temp.difference - temp.laterQuantity;
        temp.laterQuantity = 0;
      } else {
        this.selectObj.warehouses.splice(
          this.selectObj.warehouses.findIndex((res) => res.warId == e.warId),
          1
        );
      }
    },
    //自己选择的仓库修改了
    myWareListChange(e1, e2) {
      let temp = this.selectObj.warehouses.find((res) => e1.id == res.warId);
      if (temp) {
        if (temp.type) {
          this.$message.warning("该仓库已删除不能选");
        } else {
          this.$message.warning("该仓库已存在");
        }
        return;
      }
      e2.warId = e1.id + "";
      e2.warName = e1.name;
      this.$forceUpdate();
    },
    //添加自己的仓库
    addMyWareList() {
      if (this.selectObj.warehouses.length < this.wareList.list.length) {
        this.selectObj.warehouses.push({
          difference: 0, //差异,减的是负数,加的是整数
          frontQuantity: 0, //调拨前库存
          laterQuantity: 0, //调拨后库存
          warId: "", //仓库id
          warName: "", //仓库名称
        });
      } else {
        this.$message.warning("不能再加了仓库只有这些");
      }
    },
    selectClick() {},
    //往el-select里面加入一个管理按钮
    visibleChange(visible, refName, onClick) {
      if (visible) {
        const ref = this.$refs[refName];
        let popper = ref.$refs.popper;
        if (popper.$el) popper = popper.$el;
        if (
          !Array.from(popper.children).some(
            (v) => v.className === "el-cascader-menu__list"
          )
        ) {
          const el = document.createElement("ul");
          el.className = "el-cascader-menu__list";
          el.style =
            "border-top: solid 1px #E4E7ED; padding:0; color: #606266;";
          el.innerHTML = `<li class="el-cascader-node" style="height:38px;line-height: 38px">
<i class="el-icon-menu"></i>
<span class="el-cascader-node__label">管理</span>
<i class="el-icon-arrow-right el-cascader-node__postfix"/>
</li>`;
          popper.appendChild(el);
          el.onclick = () => {
            // 底部按钮的点击事件 点击后想触发的逻辑也可以直接写在这
            this.getWhyList();
            this.dialogFormVisible = true;
            // 以下代码实现点击后弹层隐藏 不需要可以删掉
            if (ref.toggleDropDownVisible) {
              ref.toggleDropDownVisible(false);
            } else {
              ref.visible = false;
            }
          };
        }
      }
    },
  },
  directives: {
    focus: {
      inserted: (el) => {
        el.focus();
      },
    },
  },
};
</script>
<style scoped lang="scss">
.nodate {
  text-align: center;
  padding: 10px 0;
  img {
    width: 120px;
    height: 120px;
    display: block;
    margin: 0 auto;
  }
  span {
    font-size: 14px;
    color: #999;
    display: inline;
    margin-top: 10px;
  }
}
.content {
  .submit {
    background: #fff;
    padding: 10px;
    width: 99%;
    text-align: right;
    border-radius: 5px;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
  }
  .context {
    display: flex;
    width: 100%;
    height: 95%;
    margin-top: 20px;
    justify-content: space-between;
    min-width: 800px;
    min-height: 800px;
    .left {
      overflow: auto;
      height: 100%;
      width: 59%;
      background: #fff;
      border-radius: 10px;
      padding: 10px 20px;
      box-sizing: border-box;
      .top {
        border-bottom: 1px solid #d9d9d9;
        padding: 10px 0px;
        font-size: 18px;
        color: #606060;
        line-height: 25px;
      }
      .tableBorder {
        border: 1px solid #d9d9d9;
        margin-top: 10px;
        .title {
          display: flex;
          flex-wrap: nowrap;
          justify-content: space-between;
          border-bottom: 1px solid #d9d9d9;
          font-size: 14px;
          padding: 10px 10px;
        }
      }
    }
    .right {
      width: 40%;
      height: 100%;
      border-radius: 10px;
      background: #fff;
      padding: 10px 20px;
      box-sizing: border-box;
      color: #333333;

      .title {
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #d9d9d9;
        padding: 10px 0px;
        margin-bottom: 5px;
      }
    }
  }
}
.dialogContent {
  .add {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .whyList {
    border: 1px solid #d9d9d9;
    margin-left: 10px;
    .item {
      margin-top: 10px;
      margin-left: 10px;
    }
  }
}
</style>
